import { onMounted, watch, computed, nextTick } from "vue";
import {
  changeMapStyle,
  toggleCluster,
  getMap,
  loadAddIcon,
  removeIcon,
  releaseResources,
  updateActualPointsProperties,
  loadRadar,
  removeRadar,
  setThresholds,
  addImage,
  removeImage,
} from "@/components/mapbox/main/index.js";
import {
  mapConfigList,
  generateMapThumbnail,
} from "@/components/mapbox/mapbox_config/mapConfigManager";
import { getDevTypeList, getRadarByTime, getSysDictData } from "@/api/device";
import { showNotify, showToast } from "vant";
import { getAssets } from "@/utils/index.js";
export default defineComponent({
  setup(props) {
    // 创建响应式状态
    const state = reactive({
      showMapLayer: false,
      mapPreviews: {},
      showSitePanel: false,
      panelHeight: 200,
      panelAnchors: [200, 300],
      isAdvancedMode: false,
      showDragHint: true,
      deviceList: [
        {
          label: "antiaircraftGun",
          name: "高炮",
          icon: getAssets("images/equipment/antiaircraftGun5.png"),
          checked: false,
          count: 0,
        },
        {
          label: "rocket",
          name: "火箭",
          icon: getAssets("images/equipment/rocket5.png"),
          checked: false,
          count: 0,
        },
        {
          label: "smokeStove",
          name: "烟炉",
          icon: getAssets("images/equipment/smokeStove5.png"),
          checked: false,
          count: 0,
        },
      ],
      settings: {
        cluster: true,
        showLabel: true,
        iconSize: 0.2,
      },
      pointGeojson: {},
      pointType: "",
      radarType: null,
      // 雷达面板状态
      showRadarPanel: false,
      radarPanelHeight: 260,
      radarPanelAnchors: [260, 650],
      isRadarAdvancedMode: false,
      showRadarDragHint: true,

      // 雷达设置
      radarSettings: {
        selectedElementKey: "",
        selectedElement: null,
        autoPlay: false,
        playInterval: null,
        thresholds: [0, 18], // 默认阈值范围
        startTime: "",
        endTime: "",
        // 添加拾点坐标初始化
        pickingPoints: [
          { lat: "", lng: "" },
          { lat: "", lng: "" },
        ],
      },

      // 雷达要素列表
      radarElements: [],

      // 雷达时间数据
      radarTimes: [],
      currentTimeIndex: 0,
      // currentRadarTime: new Date().toISOString().slice(0, 10),
      currentRadarTime: new Date("2025-02-24").toISOString().slice(0, 10),

      tempSelectedDate: [
        // String(new Date().getFullYear()),
        // String(new Date().getMonth() + 1),
        // String(new Date().getDate()),
        "2025",'02','24'
      ],
      showCurrentTimePicker: false,
    });

    // 在setup函数中添加计算属性
    const radarTimeColumns = computed(() => {
      return state.radarTimes.map((time) => {
        const date = new Date(time);
        const hours = String(date.getHours()).padStart(2, "0");
        const minutes = String(date.getMinutes()).padStart(2, "0");
        return `${hours}:${minutes}`;
      });
    });

    // 监听面板高度变化，更新面板状态
    watch(
      () => state.panelHeight,
      (newHeight) => {
        state.isAdvancedMode = newHeight > state.panelAnchors[0] + 50;
        if (state.isAdvancedMode && state.showDragHint) {
          setTimeout(() => {
            state.showDragHint = false;
          }, 3000);
        }
      }
    );

    // 监听雷达面板高度变化
    watch(
      () => state.radarPanelHeight,
      (newHeight) => {
        state.isRadarAdvancedMode = newHeight > state.radarPanelAnchors[0] + 50;
        if (state.isRadarAdvancedMode && state.showRadarDragHint) {
          setTimeout(() => {
            state.showRadarDragHint = false;
          }, 3000);
        }
      }
    );

    // 监听雷达自动播放状态变化
    watch(
      () => state.radarSettings.autoPlay,
      (newAutoPlay) => {
        if (newAutoPlay) startRadarAutoPlay();
        else stopRadarAutoPlay();
      }
    );

    // 监听雷达要素变化
    watch(
      () => state.radarSettings.selectedElementKey,
      (newElementKey) => {
        if (newElementKey) {
          if (state.radarTimes.length > 0) {
            methods.selectRadarTimeByIndex(state.currentTimeIndex);
          } else {
            methods.fetchTimeButtons();
          }
        }
      }
    );

    const methods = {
      async getDictData() {
        try {
          let data = await getSysDictData({ dictType: "radar_type" });
          state.radarElements = data.data;
          if (state.radarElements?.length > 0) {
            this.selectRadarElement(state.radarElements[0].dictValue);
          }
        } catch (error) {
          console.error("获取雷达要素列表失败:", error);
          showToast("获取雷达要素列表失败");
        }
      },

      processTimeButtonData(data) {
        return data.map((item) => ({
          label: methods.formatTime(item.dataTime),
          value: item.dataTime,
          dataType: item.dataType,
          filePath: item.filePath,
          coordinate: [
            [item.longiMin, item.latiMin],
            [item.longiMax, item.latiMin],
            [item.longiMax, item.latiMax],
            [item.longiMin, item.latiMax],
          ],
        }));
      },

      /**
       * 获取时间轴数据
       * @description 从服务器获取雷达时间点数据，并在获取成功后加载显示
       */
      async fetchTimeButtons() {
        try {
          if (!state.radarSettings.selectedElementKey) {
            console.warn("未选择雷达要素，无法获取时间数据");
            return;
          }

          showToast({ message: "正在加载时间数据...", duration: 1000 });

          const res = await getRadarByTime({
            dataTime: state.currentRadarTime + " 00:00:00",
            divine: false,
            radarType: state.radarSettings.selectedElementKey,
          });

          if (res.code === 200) {
            if (res.data?.radarFileVoList?.length > 0) {
              try {
                state.radarTimes = methods.processTimeButtonData(
                  res.data.radarFileVoList
                );

                if (state.radarTimes.length > 0) {
                  const lastIndex = state.radarTimes.length - 1;

                  methods.clearRadarLayer();

                  methods.selectRadarTimeByIndex(lastIndex);
                  
                  // 确保滚动到选中的时间点
                  methods.scrollToCurrentTimePoint();
                } else {
                  showToast("时间数据解析失败，无可用雷达数据");
                }
              } catch (processError) {
                methods.handleError(processError, "处理时间数据失败");
              }
            } else {
              state.radarTimes = [];
              showToast({
                message: "未获取到雷达时间数据，请尝试其他日期",
                duration: 2000,
              });
            }
          } else {
            showToast({
              message: res.msg || "获取时间数据失败",
              type: "fail",
              duration: 2000,
            });
          }
        } catch (error) {
          showToast({
            message: "获取时间数据失败",
            type: "fail",
            duration: 2000,
          });
        }
      },

      handleMapClick(type) {
        switch (type) {
          case "mapLayer":
            state.showMapLayer = !state.showMapLayer;
            break;
          case "site":
            if (state.showRadarPanel) methods.closeRadarPanel();
            if (!state.showSitePanel) {
              const screenHeight = window.innerHeight;
              state.panelAnchors = [
                Math.round(0.3 * screenHeight),
                Math.round(0.65 * screenHeight),
              ];
              state.panelHeight = state.panelAnchors[0];
              state.showSitePanel = true;
              state.isAdvancedMode = false;
              state.showDragHint = true;
            }

            const images = ["antiaircraftGun", "rocket", "smokeStove"];
            map = getMap();
            for (let i = 0; i < images.length - 1; i++) {
              for (let j = 0; j < 5; j++) {
                loadAddIcon(
                  map,
                  `${images[i]}${j}`,
                  getAssets(`images/equipment/${images[i]}${j}.png`),
                  () => {}
                );
              }
            }
            loadAddIcon(
              map,
              "position",
              getAssets(`images/equipment/position-removebg-preview.png`),
              () => {}
            );
            break;
          case "radar":
            if (state.showSitePanel) methods.closeSitePanel();
            if (!state.showRadarPanel) {
              methods.initRadarPanel();
            }
            break;
        }
      },

      closeSitePanel() {
        state.showSitePanel = false;
      },

      closeRadarPanel() {
        stopRadarAutoPlay();
        if (state.radarSettings.selectedElementKey) {
          methods.clearRadarLayer();
        }
        state.showRadarPanel = false;
      },

      handleMapLayerClick(layer) {
        try {
          changeMapStyle(layer.url);
          showNotify({ type: "success", message: `已切换至${layer.name}` });
          state.showMapLayer = false;
        } catch (error) {
          console.error(error);
        }
      },

      handleDeviceClick(device) {
        device.checked = !device.checked;
        if (device.checked) {
          methods.getPointList(device.label);
        } else {
          device.count = 0;
          releaseResources(map, device.label);
        }
      },

      // 获取点位数据
      async getPointList(type) {
        try {
          const res = await getDevTypeList({ devType: type });
          if (res.code == 200) {
            state.deviceList.find((item) => item.label == type).count =
              res.data.length;
            let geojson = {
              type: "FeatureCollection",
              features: res.data.map((item) => ({
                type: "Feature",
                properties: {
                  data: item,
                  imageName: type + "0",
                  label: item.pointName,
                  type: item.id,
                  showLabel: state.settings.showLabel,
                  iconSize: state.settings.iconSize,
                },
                geometry: {
                  type: "Point",
                  coordinates: [item.pointLongi, item.pointLati],
                },
              })),
            };
            state.pointGeojson = geojson;
            state.pointType = type;
            toggleCluster(getMap(), type, geojson, true);
          }
        } catch (error) {
          console.error(error);
        }
      },

      //点位图标大小调整
      handleIconSizeChange() {
        updateActualPointsProperties(getMap(), state.pointType, {
          "icon-size": state.settings.iconSize,
          "text-size": 12,
        });
      },

      // 聚合变更
      handleClusterChange(value) {
        toggleCluster(getMap(), state.pointType, state.pointGeojson, value);
      },

      // 格式化时间显示
      formatDateTime(timestamp) {
        if (!timestamp) return "";
        const date = new Date(timestamp);
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, "0");
        const day = String(date.getDate()).padStart(2, "0");
        const hours = String(date.getHours()).padStart(2, "0");
        const minutes = String(date.getMinutes()).padStart(2, "0");
        return `${year}-${month}-${day} ${hours}:${minutes}`;
      },

      // 格式化时间点显示
      formatTime(timestamp) {
        if (!timestamp) return "";
        try {
          if (typeof timestamp === "string" && timestamp.includes("-")) {
            const parts = timestamp.split(" ");
            if (parts.length >= 2) {
              const timeParts = parts[1].split(":");
              if (timeParts.length >= 2) {
                return `${timeParts[0]}:${timeParts[1]}:${timeParts[2]}`;
              }
            }
          }

          const date = new Date(timestamp);
          if (!isNaN(date.getTime())) {
            const hours = String(date.getHours()).padStart(2, "0");
            const minutes = String(date.getMinutes()).padStart(2, "0");
            const seconds = String(date.getSeconds()).padStart(2, "0");
            return `${hours}:${minutes}:${seconds}`;
          }
          return typeof timestamp === "string" ? timestamp : String(timestamp);
        } catch (error) {
          console.error("格式化时间出错:", error);
          return String(timestamp);
        }
      },

      // 切换自动播放
      toggleAutoPlay() {
        state.radarSettings.autoPlay = !state.radarSettings.autoPlay;
        if (state.radarSettings.autoPlay) {
          if (!state.radarTimes || state.radarTimes.length < 2) {
            showToast("时间点数量不足，无法自动播放");
            state.radarSettings.autoPlay = false;
            return;
          }
          startRadarAutoPlay();
          showToast("已开启自动播放");
        } else {
          stopRadarAutoPlay();
          showToast("已停止自动播放");
        }
      },

      // 重置雷达时间
      resetRadarTime() {
        if (!state.radarTimes || state.radarTimes.length === 0) {
          showToast("没有可用的时间数据");
          return;
        }
        methods.selectRadarTimeByIndex(0);
        showToast("已重置到最早时间点");
      },

      /**
       * 选择雷达要素
       * @param {string} element 雷达要素ID
       * @description 设置当前选中的雷达要素，清除现有图层，获取时间轴数据
       */
      selectRadarElement(element) {
        console.log(element);

        state.radarSettings.selectedElementKey = element;
        state.radarSettings.selectedElement =
          state.radarElements.find((item) => item.dictValue === element) ||
          null;
        state.radarTimes = [];
        state.currentTimeIndex = 0;
        this.clearRadarLayer();
      },

      /**
       * 清除雷达图层
       * @description 移除地图上所有雷达相关图层
       */
      clearRadarLayer() {
        const map = getMap();
        if (!map) return;

        try {
          if (state.radarType == 0) {
            removeImage(map, "radarPng");
          } else {
            removeImage(map, "radarPng");
            removeRadar(map, "radarTif");
          }
        } catch (error) {
          console.error("清除雷达图层出错:", error);
        }
      },

      /**
       * 选择雷达时间点
       * @param {number} index 时间点的索引
       * @param {Object} selectedTime 选中的时间点数据
       * @description 根据选择的时间点渲染对应的雷达图层
       */
      selectRadarTime(index, selectedTime) {
        const map = getMap();
        if (!map) {
          showToast("地图实例未找到");
          return;
        }

        if (!selectedTime) {
          console.warn("未提供时间点数据，无法渲染雷达");
          return;
        }

        state.currentTimeIndex = index;
        if (selectedTime.value) {
          state.currentRadarTime = selectedTime.value;
          state.radarType = selectedTime.dataType;
        }

        try {
          methods.clearRadarLayer();

          try {
            const processedFilePath = selectedTime.filePath;

            if (selectedTime.dataType == 1) {
              try {
                loadRadar(
                  map,
                  "radarTif",
                  processedFilePath,
                  selectedTime.coordinate
                )
                  .then(() => {
                    setThresholds(state.radarSettings.thresholds);
                  })
                  .catch((err) => {
                    console.error("TIF加载失败详情:", err);
                    methods.handleError(err, "TIF雷达图层加载失败");
                  });
              } catch (err) {
                console.error("TIF加载失败详情:", err);
                methods.handleError(err, "TIF雷达图层加载失败");
              }
            } else {
              // PNG等图片格式处理
              try {
                addImage(
                  map,
                  "radarPng",
                  processedFilePath,
                  selectedTime.coordinate
                );
              } catch (err) {
                methods.handleError(err, "雷达图片加载失败");
              }
            }
          } catch (delayedError) {
            methods.handleError(delayedError, "延迟加载雷达图层失败");
          }
          
          // 滚动到当前时间点
          methods.scrollToCurrentTimePoint();
        } catch (error) {
          methods.handleError(error, "切换雷达时间点出错");
        }
      },

      // 阈值变更处理
      handleThresholdChange(value) {
        setThresholds(value);
      },

      // 获取点位置
      getLocationForPoint(pointIndex) {
        showToast("请在地图上点击选择位置");
        const map = getMap();
        if (!map) return;

        const clickListener = function (e) {
          const coords = e.lngLat;
          state.radarSettings.pickingPoints[pointIndex].lng =
            coords.lng.toFixed(6);
          state.radarSettings.pickingPoints[pointIndex].lat =
            coords.lat.toFixed(6);
          showToast(`已设置第${pointIndex + 1}个点的坐标`);
          map.off("click", clickListener);
        };

        map.once("click", clickListener);
      },

      // 生成剖面
      generateProfile() {
        const point1 = state.radarSettings.pickingPoints[0];
        const point2 = state.radarSettings.pickingPoints[1];

        if (!point1.lat || !point1.lng || !point2.lat || !point2.lng) {
          showToast("请先设置两个点的坐标");
          return;
        }

        showToast("剖面拾点成功，正在生成剖面数据...");
        console.log(
          `从 (${point1.lat}, ${point1.lng}) 到 (${point2.lat}, ${point2.lng}) 生成剖面`
        );
      },

      // 重置拾点
      resetPickingPoints() {
        state.radarSettings.pickingPoints.forEach((point) => {
          point.lat = "";
          point.lng = "";
        });
        showToast("已重置拾点坐标");
      },

      // 刷新剖面
      refreshProfile() {
        const point1 = state.radarSettings.pickingPoints[0];
        const point2 = state.radarSettings.pickingPoints[1];

        if (!point1.lat || !point1.lng || !point2.lat || !point2.lng) {
          showToast("请先设置两个点的坐标");
          return;
        }
        showToast("正在刷新剖面数据...");
      },

      // 处理日期时间选择确认
      onDateTimeConfirm(value) {
        const formattedDate = formatDateTime(value);
        methods.changeRadarDate(formattedDate);
      },

      /**
       * 处理日期选择确认
       * @param {Object} param0 选择的日期值
       * @description 处理日期选择器确认后的操作，更新当前日期并获取新的时间轴数据
       */
      onDateConfirm({ selectedValues }) {
        if (Array.isArray(selectedValues) && selectedValues.length >= 3) {
          const year = selectedValues[0];
          const month = String(selectedValues[1]).padStart(2, "0");
          const day = String(selectedValues[2]).padStart(2, "0");

          const formattedDate = `${year}-${month}-${day}`;
          state.showCurrentTimePicker = false;

          methods.changeRadarDate(formattedDate);
        } else {
          showToast("日期选择错误，请重试");
        }
      },

      // 处理错误
      handleError(error, defaultMessage = "操作失败") {
        let message = defaultMessage;

        if (error.message && error.message.includes("CORS")) {
          message = "跨域访问受限，无法加载雷达数据";
          showToast({
            message: message,
            type: "fail",
            duration: 3000,
          });
          return;
        }

        if (error.message) {
          message = error.message;
        }

        showToast({
          message: message,
          type: "fail",
          duration: 2000,
        });

        console.error("操作错误:", error);
      },

      /**
       * 根据索引选择雷达时间点
       * @param {number} index 要选择的时间点索引
       * @returns {boolean} 是否成功选择时间点
       * @description 根据索引从时间轴数据中选择时间点进行渲染
       */
      selectRadarTimeByIndex(index) {
        if (
          !state.radarTimes ||
          state.radarTimes.length === 0 ||
          index < 0 ||
          index >= state.radarTimes.length
        ) {
          console.warn("无效的时间点索引或时间轴为空");
          return false;
        }

        const selectedTime = state.radarTimes[index];
        if (!selectedTime) {
          console.warn("无法获取时间点数据");
          return false;
        }

        try {
          methods.selectRadarTime(index, selectedTime);
          return true;
        } catch (error) {
          methods.handleError(error, "选择时间点失败");
          return false;
        }
      },

      /**
       * 雷达面板初始化
       * @description 初始化雷达面板的尺寸和状态，获取雷达要素列表
       */
      initRadarPanel() {
        const screenHeight = window.innerHeight;
        state.radarPanelAnchors = [
          Math.round(0.4 * screenHeight),
          Math.round(0.65 * screenHeight),
        ];
        state.radarPanelHeight = state.radarPanelAnchors[0];
        state.showRadarPanel = true;
        state.isRadarAdvancedMode = false;
        state.showRadarDragHint = true;

        // 获取雷达要素列表
        methods.getDictData();
      },

      /**
       * 改变雷达日期
       * @param {string} date 新的日期字符串
       * @description 更新雷达当前日期，清除旧数据，并获取新的时间轴数据
       */
      changeRadarDate(date) {
        if (!date) return;

        state.currentRadarTime = date;
        state.radarTimes = [];
        methods.clearRadarLayer();

        methods.fetchTimeButtons();
      },

      /**
       * 滚动到当前选中的时间点
       * @description 使时间轴滚动到当前选中的时间点位置，使其可见
       */
      scrollToCurrentTimePoint() {
        // 使用 nextTick 确保 DOM 已更新
        nextTick(() => {
          try {
            const container = document.querySelector('.time-axis-container');
            const activePoint = document.querySelector('.time-point.active');
            
            if (container && activePoint) {
              // 计算需要滚动的位置 - 使活动点居中
              const containerWidth = container.offsetWidth;
              const activePointLeft = activePoint.offsetLeft;
              const activePointWidth = activePoint.offsetWidth;
              
              // 计算滚动位置，使活动点居中
              const scrollPosition = activePointLeft - (containerWidth / 2) + (activePointWidth / 2);
              
              // 平滑滚动到该位置
              container.scrollTo({
                left: Math.max(0, scrollPosition),
                behavior: 'smooth'
              });
            }
          } catch (error) {
            console.error('滚动到当前时间点出错:', error);
          }
        });
      },

      /**
       * 滚动时间轴
       * @param {string} direction 滚动方向，'left'或'right'
       * @description 按指定方向滚动时间轴容器
       */
      scrollTimeAxis(direction) {
        try {
          const container = document.querySelector('.time-axis-container');
          if (!container) return;
          
          // 计算滚动距离 - 容器宽度的一半
          const scrollDistance = Math.floor(container.offsetWidth / 2);
          
          // 当前滚动位置
          const currentScroll = container.scrollLeft;
          
          // 根据方向滚动
          if (direction === 'left') {
            container.scrollTo({
              left: Math.max(0, currentScroll - scrollDistance),
              behavior: 'smooth'
            });
          } else {
            container.scrollTo({
              left: currentScroll + scrollDistance,
              behavior: 'smooth'
            });
          }
        } catch (error) {
          console.error('滚动时间轴出错:', error);
        }
      },
    };

    /**
     * 启动雷达自动播放
     * @description 以固定时间间隔循环播放雷达时间序列
     */
    function startRadarAutoPlay() {
      try {
        if (state.radarSettings.playInterval) {
          clearInterval(state.radarSettings.playInterval);
          state.radarSettings.playInterval = null;
        }

        if (!state.radarTimes || state.radarTimes.length < 2) {
          console.warn("时间点数量不足，无法自动播放");
          state.radarSettings.autoPlay = false;
          return;
        }

        // 设置自动播放定时器，每4秒切换一次
        state.radarSettings.playInterval = setInterval(() => {
          try {
            let nextIndex = state.currentTimeIndex + 1;
            if (nextIndex >= state.radarTimes.length) {
              nextIndex = 0;
            }

            methods.selectRadarTimeByIndex(nextIndex);
          } catch (error) {
            console.error("自动播放循环出错:", error);
            stopRadarAutoPlay();
            showToast("自动播放出错，已停止");
          }
        }, 2000);

        console.log("自动播放已启动");
      } catch (error) {
        console.error("启动自动播放出错:", error);
        state.radarSettings.autoPlay = false;
        showToast("启动自动播放失败");
      }
    }

    /**
     * 停止雷达自动播放
     * @description 清除自动播放定时器并重置状态
     */
    function stopRadarAutoPlay() {
      try {
        if (state.radarSettings.playInterval) {
          clearInterval(state.radarSettings.playInterval);
          state.radarSettings.playInterval = null;
          console.log("自动播放已停止");
        }
      } catch (error) {
        console.error("停止自动播放出错:", error);
      } finally {
        state.radarSettings.playInterval = null;
        state.radarSettings.autoPlay = false;
      }
    }

    onMounted(async () => {
      for (const layer of mapConfigList) {
        try {
          const previewUrl = await generateMapThumbnail(layer);
          state.mapPreviews[layer.key] = previewUrl;
        } catch (error) {
          state.mapPreviews[layer.key] = layer.thumbnail || "";
        }
      }
    });

    onBeforeUnmount(() => {
      const images = ["antiaircraftGun", "rocket", "smokeStove"];
      for (let i = 0; i < images.length - 1; i++) {
        for (let j = 0; j < 5; j++) {
          removeIcon(map, `${images[i]}${j}`);
        }
      }
      removeIcon(map, "position");

      // 清理雷达资源
      if (state.showRadarPanel && state.radarSettings.selectedElement) {
        stopRadarAutoPlay();
        methods.clearRadarLayer();
      }
    });

    return {
      ...toRefs(state),
      ...methods,
      mapConfigList,
      radarTimeColumns,
    };
  },
});
